package com.dk.shiro;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dk.pojo.TPerson;
import com.dk.service.MenuService;
import com.dk.service.PerosnService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class LoginRealm extends AuthorizingRealm {
    @Reference
    private PerosnService perosnService;
    @Reference
    private MenuService menuService;
   //授权逻辑的方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权方法");
        //根据登录用户查询数据库，看数据库中是否有该权限字符串
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //从数据库 查询 权限字符串
        TPerson person = (TPerson)SecurityUtils.getSubject().getPrincipal();
        //根据登录id查询用户所拥有的字符串
        List<String> perms = menuService.findPermsByPersonId(person.getPid());
        info.addStringPermissions(perms);
        return info;
    }
    //编写认证逻辑的方法（登录）
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        TPerson person = perosnService.selectByPname(token.getUsername());
        if (person == null){
            return null;
        }

       //参数位置 1 , 登录后的用户对象。2,3:数据库查询出来的用户名和密码
        return new SimpleAuthenticationInfo(person,person.getPwd(), ByteSource.Util.bytes(person.getSalt()),person.getPname());
    }

}
